/**
 * 维护现场时间弹框
 */
import React, { useEffect, memo, useState } from 'react';
import { Modal, Button, Input, DatePicker, TimePicker, Spin } from 'antd';
import { useBoolean, useRequest } from '@umijs/hooks';
import moment from 'moment';
import { getOrderSceneList, saveOrderScene } from '../../service';
import { intervalTime } from '@/utils/utils'; //格式化时间

import styles from './index.less';

let timer = null; // 定时器
const MaintainTime = props => {
  const { timeId, modalVisible, setToggleMaintainTimeFalse } = props;
  const [countdownSeconds, setCountdownSeconds] = useState(0); // 倒计时秒数
  const [getInfo, setgetInfo] = useState([]); // 当前现场领取时间信息格式化之后的数据
  const [startData, setstartData] = useState(new Date(moment(new Date()).format('YYYY-MM-DD'))); // 初始日期
  const [startTime, setstartTime] = useState('00'); // 初始时间

  const [effectiveTime, setEffectiveTime] = useState(0); //连续生效时长
  const [validTime, setValidTime] = useState(0); //剩余有效时长
  
  // 获取维护现场时间
  const { run: getSiteTime, loading } = useRequest(params => getOrderSceneList(params), {
    manual: true,
    onSuccess: data => {
      clearInterval(timer);
      timer = null;
      if (data.length === 0) {
        return;
      }
      
      // 剩余有效时间  effectiveTime+startTime-当前时间
      setValidTime((new Date(moment(data[0].startTime).add(data[0].effectiveTime, 's').format('YYYY-MM-DD HH:mm:ss')) - new Date(moment(new Date()).format('YYYY-MM-DD HH:mm:ss'))) / 1000);
      // 连续生效时长 当前时间-startTime
      setEffectiveTime((new Date(moment(new Date()).format('YYYY-MM-DD HH:mm:ss')) - new Date(moment(data[0].startTime).format('YYYY-MM-DD HH:mm:ss'))) / 1000);
      
      setstartTime(moment(data[0].startTime).add(data[0].effectiveTime, 's').format('HH'));
      setstartData(moment(data[0].startTime).add(data[0].effectiveTime, 's').format('YYYY-MM-DD'));
      setgetInfo(data);
    },
  });

  // 保存维护时间
  const { run: saveSiteTime, loading: saveLoading } = useRequest(params => saveOrderScene(params), {
    manual: true,
    onSuccess: data => {
      getSiteTime(timeId);
    },
  });

  //获取维护时间信息
  useEffect(() => {
    getSiteTime(timeId);
  }, [timeId]);

  // 确定修改
  const handleOk = () => {
    Modal.confirm({
      title: '提示',
      content: '确认修改现场领取失效时间吗？',
      onOk() {
        const s_time = new Date(
          moment(new Date(startData + ' ' + startTime + ':' + moment(getInfo[0].startTime).format('mm:ss'))).format('YYYY-MM-DD HH:mm:ss'));
        const e_time = new Date(moment(getInfo[0].startTime).format('YYYY-MM-DD HH:mm:ss'));
        saveSiteTime({
          orderId: timeId.orderId,
          startTime: getInfo[0].startTime, // 补偿单确认发放时间
          type: '发起', // 维护类型（发起，修改）
          effectiveTime: (s_time - e_time) / 1000, //有效时长（秒）
        });
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  // 选择时间
  const onChangeTime = (time, timeStr) => {
    setstartTime(timeStr);
  };
  // 选择日期
  const onChangeData = (time, timeStr) => {
    setstartData(timeStr);
  };
  // 弹框关闭
  const modalCancelFun = () => {
    clearInterval(timer);
    timer = null;
    setToggleMaintainTimeFalse();
  };

  /**
   * @description 副作用函数处理倒计时显示
   */
  useEffect(() => {
    if (validTime <= 0) {
      clearInterval(timer);
          timer = 'over';
          setValidTime(n => {
            return 0;
          });
          setEffectiveTime(getInfo.length > 0 ? getInfo[0].effectiveTime : 0);
    }
    if (!timer) {
      timer = setInterval(() => {
        if (validTime > 0) {
          setEffectiveTime(n => {
            return n + 1;
          });
          setValidTime(n => {
            return n - 1;
          });
        }
      }, 1000);
    }
  }, [validTime,getInfo]);

  useEffect(() => {
    if (timer) {
      clearInterval(timer);
      timer = null;
    }
  }, []);

  return (
    <>
      <Modal
        title="维护现场时间"
        visible={modalVisible}
        width="600px"
        destroyOnClose={true}
        maskClosable={false}
        footer={null}
        onCancel={modalCancelFun}
      >
        <Spin tip="Loading..." spinning={loading}>
          <div className={styles.maintainTimeBox}>
            <p className={styles.title}>当前现场领取时间信息</p>
            <div className={styles.timeItem}>
              现场领取有效时间：
              <Input
                style={{ width: '360px' }}
                value={
                  getInfo.length > 0
                    ? `${getInfo[0].startTime} 至 ${moment(getInfo[0].startTime)
                        .add(getInfo[0].effectiveTime, 's')
                        .format('YYYY-MM-DD HH:mm:ss')}`
                    : ''
                }
                disabled
                placeholder="现场领取有效时间"
              />
            </div>
            <div className={styles.timeItem}>
              连续生效时长：
              <Input
                style={{ width: '360px' }}
                value={intervalTime(effectiveTime)}
                disabled
                placeholder="连续生效时长"
              />
            </div>
            <div className={styles.timeItem}>
              剩余有效时间：
              <Input
                style={{ width: '360px' }}
                value={intervalTime(validTime)}
                disabled
                placeholder="剩余有效时间"
              />
            </div>
            {/* 维护记录 */}
            <p className={styles.title} style={{ marginTop: '20px' }}>
              维护记录
            </p>
            <ul className={styles.listItemBox}>
              <li style={{ fontWeight: '600' }}>
                <span style={{ width: '35%' }}>维护时间</span>
                <span style={{ width: '20%' }}>维护人</span>
                <span style={{ width: '20%' }}>维护类型</span>
                <span style={{ width: '25%' }}>失效时间设置</span>
              </li>
              {getInfo &&
                getInfo.map(item => {
                  return (
                    <li key={item.id}>
                      <span style={{ width: '35%' }}>{item.createTime}</span>
                      <span style={{ width: '20%' }}>{item.serviceUser}</span>
                      <span style={{ width: '20%' }}>{item.type}</span>
                      <span style={{ width: '25%' }}>{moment(item.startTime).add(item.effectiveTime, 's').format('YYYY-MM-DD HH')} 时</span>
                    </li>
                  );
                })}
            </ul>
            {/* 现场领取失效时间 */}
            <p className={styles.title} style={{ marginTop: '20px' }}>
              现场领取失效时间
            </p>
            <DatePicker
              onChange={onChangeData}
              allowClear={false}
              value={moment(startData, 'YYYY-MM-DD')}
              format="YYYY-MM-DD"
            />
            <TimePicker
              onChange={onChangeTime}
              allowClear={false}
              value={moment(startTime, 'HH')}
              format="HH"
              style={{ marginLeft: '10px', width: '100px' }}
            />{' '}
            时
            <span style={{ marginLeft: '14px', marginRight: '40px' }}>
              {getInfo.length > 0 ? `${moment(getInfo[0].startTime).format('mm')}` : '0'} 分
            </span>
            {/* 修改按钮 */}
            <Button
              type="primary"
              onClick={handleOk}
              loading={saveLoading}
              disabled={getInfo.length === 0}
            >
              修改
            </Button>
          </div>
        </Spin>
      </Modal>
    </>
  );
};

/**
 * 优化渲染
 */
function carefulRender(prevProps, nextProps) {
  if (prevProps.modalVisible != nextProps.modalVisible) {
    return false;
  } else {
    return true;
  }
}

export default memo(MaintainTime, carefulRender);
